﻿using CommandFlags = Dapper.CommandFlags;

namespace Anley.DomainDrivenDesign.Contract.Helper;

/// <summary>
/// 文件帮助类
/// </summary>
public class FileHelper
    : IFileHelper
{
    // 生成本地路径
    public string GenerateLocalPath(
        params string[] pathes)
    {
        for (int i = 0; i < pathes.Length; i++)
        {
            ArgumentNullException.ThrowIfNull(pathes[i]);
            if (i == 0)
                continue;
            pathes[i] = pathes[i].Replace("/", @"\");
            if (pathes[i].StartsWith(@"\"))
                pathes[i] = pathes[i].Substring(1);
        }
        return Path.Combine(pathes);
    }

    // Dapper保存至Excel
    public async Task DapperToExcelAsync(
        IDbConnection connection,
        string queryString,
        string filePath)
    {
        var command = new CommandDefinition(queryString, flags: CommandFlags.NoCache);
        var rows = await connection.ExecuteReaderAsync(command);
        await MiniExcel.SaveAsAsync(filePath, rows);
    }

    // 数据源保存至Word
    public void DataSourceToWord(
        IMailMergeDataSource source,
        string templatePath,
        string filePath)
    {
        var doc = new Document(templatePath);
        doc.MailMerge.Execute(source);
        doc.Save(filePath);
    }

    // 数据源保存至PDF
    public void DataSourceToPdf(
        IMailMergeDataSource source,
        string wordTemplatePath,
        string filePath)
    {
        var doc = new Document(wordTemplatePath);
        doc.MailMerge.Execute(source);
        doc.Save(filePath, SaveFormat.Pdf);
    }
}